﻿using System;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Device.Location;
using System.Linq;
using _160Projects.Data;
using _160Projects.LetMeFillThatOutForYouServiceReference;
using User = _160Projects.Data.User;

namespace CapstoneMockup.ViewModels
{
    public class MainViewModel : INotifyPropertyChanged
    {
        public ObservableCollection<ThreadInfoViewModel> ForumInfoItems { get; private set; }
        public ForumThreadViewModel CurrentThread { get; private set; }
        public readonly DatabaseServiceClient WcfConnection = new DatabaseServiceClient();
        public EventHandler PostLoadComplete;
        public User User { get; set; }
        public ObservableCollection<TimeStampViewModel> TimeStampItems { get; private set; } 

        /// <summary>
        /// Sample ViewModel property; this property is used in the view to display its value using a Binding
        /// </summary>
        /// <returns></returns>

        public MainViewModel()
        {
            WcfConnection.PublishPostCompleted += PublishPostCompleted;
            WcfConnection.PublishThreadCompleted += PublishThreadCompleted;
            WcfConnection.GetThreadPostsInThreadCompleted += PostsLoaded;
            WcfConnection.RetriveExpenseLogsCompleted += (WcfConnection_RetriveExpenseLogsCompleted);
            WcfConnection.RetriveHoursCompleted += (WcfConnection_RetriveHoursCompleted);
            LoadData();
        }

        void WcfConnection_RetriveHoursCompleted(object sender, RetriveHoursCompletedEventArgs e)
        {
            var ListOfHours = e.Result;
            foreach (var listOfHour in ListOfHours)
            {
                App.ViewModel.User._hourTimeStamps.Add(new Timestamps(){EndTime = listOfHour.EndTime, StartTime = listOfHour.StartTime});
            }
            
        }

        void WcfConnection_RetriveExpenseLogsCompleted(object sender, RetriveExpenseLogsCompletedEventArgs e)
        {
            User._expenseLogs.Clear();
            
            foreach (var log in e.Result)
            {
                var parsedLog = new ExpenseLog(log.LogName);

                foreach (var expense in log.ListOfExpenise)
                {
                    var parsedExpense = new Data.Expense(expense.ItemDescription, (double) expense.Amount, expense.AccountNumber, expense.PlaceOfPuchase);

                    parsedLog._ListOfExpenses.Add(parsedExpense);
                }

                User._expenseLogs.Add(parsedLog);
            }

            if(User._expenseLogs.Count > 0)
                User._currentLog = User._expenseLogs.Last();
        }

        public bool IsDataLoaded
        {
            get;
            private set;
        }
        public void RefreshForums()
        {
            ForumInfoItems = new ObservableCollection<ThreadInfoViewModel>();

            WcfConnection.GetTenLatestsThreadsAsync();
        }
        /// <summary>
        /// Creates and adds a few ItemViewModel objects into the Items collection.
        /// </summary>
        public void LoadData()
        {
            WcfConnection.GetTenLatestsThreadsCompleted += ForumsLoaded;
            WcfConnection.GetTenLatestsThreadsAsync();

            ForumInfoItems = new ObservableCollection<ThreadInfoViewModel>();
            CurrentThread = null;

            this.IsDataLoaded = true;
        }
        public void PublishThreadCompleted(object sender, AsyncCompletedEventArgs args)
        {
            WcfConnection.GetTenLatestsThreadsAsync();
        }
        public void SetCurrentThread(int threadId)
        {
            WcfConnection.GetThreadPostsInThreadAsync(threadId);

            CurrentThread = new ForumThreadViewModel("", threadId);
        }
        private void PublishPostCompleted(object sender, AsyncCompletedEventArgs args)
        {
            WcfConnection.GetThreadPostsInThreadAsync(CurrentThread.PostId);
        }
        private void PostsLoaded(object sender, GetThreadPostsInThreadCompletedEventArgs args)
        {
            var posts = args.Result;

            CurrentThread.Posts.Clear();

            foreach (var post in posts)
            {
                GeoCoordinate location = null;

                if (post.Location != null)
                    location = new GeoCoordinate(post.Location.Latitude, post.Location.Longitude);

                CurrentThread.Posts.Add(new ForumThreadPostViewModel(post.Poster.Username, post.PostTime, post.Content, location));
            }

            PostLoadComplete(this, null);
        }
        private void ForumsLoaded(object sender, GetTenLatestsThreadsCompletedEventArgs args)
        {
            var threads = args.Result;

            ForumInfoItems.Clear();

            foreach (var thread in threads)
            {
                var parsedThread = new ThreadInfoViewModel(thread.Title,
                                                           new ForumThreadPostViewModel(thread.LatestPost.Poster.Username,
                                                                                        thread.LatestPost.PostTime,
                                                                                        thread.LatestPost.Content, null), thread.ThreadId);

                ForumInfoItems.Add(parsedThread);
            }
        }


        public void GetHours()
        {
            App.ViewModel.WcfConnection.RetriveHoursAsync(App.ViewModel.User.Id);
        }

        public void GetSaveExpenses()
        {
            App.ViewModel.WcfConnection.RetriveExpenseLogsAsync(App.ViewModel.User.Id);
        }


        public event PropertyChangedEventHandler PropertyChanged;
        private void NotifyPropertyChanged(String propertyName)
        {
            PropertyChangedEventHandler handler = PropertyChanged;
            if (null != handler)
            {
                handler(this, new PropertyChangedEventArgs(propertyName));
            }
        }
    }
}
